package com.winit.openapi.sms;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.winit.common.query.Page;
import com.winit.common.spi.SPIException;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.bpartner.vo.Bpartner;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.sms.common.SmsUtils;
import com.winit.openapi.sms.validator.IncomeSettlementFieldValidator;
import com.winit.openapi.util.DateUtil;
import com.winit.sms.spi.common.vo.PageVo;
import com.winit.sms.spi.settlement.CostSettlementService;
import com.winit.sms.spi.settlement.IncomeSettlementService;
import com.winit.sms.spi.settlement.command.QueryCostSettlementLineByTypeCommand;
import com.winit.sms.spi.settlement.command.QueryIncomeSettlementByDocTypeCommand;
import com.winit.sms.spi.settlement.command.QueryIncomeSettlementLineByTypeCommand;
import com.winit.sms.spi.settlement.command.QueryReturnMaterialCommand;
import com.winit.sms.spi.settlement.vo.CostSettlementLineVo;
import com.winit.sms.spi.settlement.vo.IncomeSettlementInfoVo;
import com.winit.sms.spi.settlement.vo.IncomeSettlementLineVo;
import com.winit.sms.spi.settlement.vo.ReturnMaterialLineVo;

/**
 * 费用单明细
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * jun.lu 	1.0  		2016年1月11日 	Created
 *
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping("/sms/incomeSettlement")
public class IncomeSettlementController extends BaseController {

    private static Logger           logger = LoggerFactory.getLogger(IncomeSettlementController.class);

    @Autowired
    private IncomeSettlementService incomeSettlementService;
    @Resource
    private CostSettlementService   costSettlementService;

    /**
     * 分页查询费用单明细
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/pageIncomeSettlement")
    public String pageIncomeSettlement(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        QueryIncomeSettlementByDocTypeCommand command = SmsUtils.toJavaObject(requestMsg.getData(),
            QueryIncomeSettlementByDocTypeCommand.class);

        CommandContext ctx = CommandContext.getContext();
        if(null == ctx){
        	logger.info(">>>>>>>>>>>调用pageIncomeSettlement接口异常，ctx对象为空");
        	return ERROR;
        }
        command.setCtx(ctx);
        Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        if (bpartner == null) {
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>bpartner对象为空");
            return ERROR;
        }

        command.setPartnerCode(bpartner.getValue());
        PageVo pageVo = SmsUtils.SetPageParams(requestMsg.getData());
        command.setPageVo(pageVo);
        if (null != command.getOrderDateTo()) {
            command.setOrderDateTo(DateUtil.spliceDate(command.getOrderDateTo()));
        }

        try {
            Page<IncomeSettlementInfoVo> pagelist = incomeSettlementService.pageIncomeSettlementBydocType(command);
            Map<String, Object> data = SmsUtils.setPageData(pagelist);
            responseMsg.setData(data);
        } catch (Exception e) {
            logger.error("<======pageIncomeSettlement：", e.getMessage());
        }
        return SUCCESS;
    }

    /**
     * 收入结算单明细导出(入库)
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/exportIncomeSettlementLine")
    public String exportIncomeSettlementLine(@ModelAttribute RequestMsg requestMsg,
                                             @ModelAttribute ResponseMsg responseMsg) {
        QueryIncomeSettlementByDocTypeCommand command = SmsUtils.toJavaObject(requestMsg.getData(),
            QueryIncomeSettlementByDocTypeCommand.class);
        Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        if (bpartner == null) {
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>bpartner对象为空");
            return ERROR;
        }
        command.setPartnerCode(bpartner.getValue());
        if (null != command.getOrderDateTo()) {
            command.setOrderDateTo(DateUtil.spliceDate(command.getOrderDateTo()));
        }
        String path = null;
        try {
            //入库
            if (command.getFlag().equals(com.winit.sms.spi.common.constant.Constants.INBOUNDTRANSACTION_IB)) {
                path = incomeSettlementService.exportInboundIncomeSettlementLine(command);
            }
            //出库
            if (command.getFlag().equals(com.winit.sms.spi.common.constant.Constants.OUTBOUNDTRANSACTION_IB)) {
                path = incomeSettlementService.exportOutboundIncomeSettlementLine(command);
            }
            if (command.getFlag().equals(com.winit.sms.spi.common.constant.Constants.ISPTRANSACTION_IB)) {
                path = incomeSettlementService.exportISPIncomeSettlementLine(command);
            }
            //退货
            if (command.getFlag().equals(com.winit.sms.spi.common.constant.Constants.RETURNMATERIALTRANSACTION_RM)) {
                path = incomeSettlementService.exportReturnMaterial(command);
            }
            //调拨
            if (command.getFlag().equals(com.winit.sms.spi.common.constant.Constants.RETURNMATERIALTRANSACTION_TF)) {
                path = incomeSettlementService.exportTransferIncomeSettlementLine(command);
            }
            logger.info("信用交易明细导出路径：{}", path);
        } catch (SPIException e) {
            logger.error(e.getMessage());
            responseMsg.setCode(e.getErrorCode());
            responseMsg.setMsg(e.getErrorMsg());
            responseMsg.setData(com.winit.sms.spi.common.constant.Constants.UPLOAD_FA);
            return ERROR;
        }
        responseMsg.setData(path);
        return SUCCESS;
    }

    /**
     * 退货交易明细查询
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/queryReturnMaterial")
    public String queryReturnMaterial(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        QueryReturnMaterialCommand command = SmsUtils.toJavaObject(requestMsg.getData(),
            QueryReturnMaterialCommand.class);
        Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        if (bpartner == null) {
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>bpartner对象为空");
            return ERROR;
        }
        command.setPartnerCode(bpartner.getValue());
        if (null != command.getOrderDateTo()) {
            command.setOrderDateTo(DateUtil.spliceDate(command.getOrderDateTo()));
        }
        
        try {
            Page<ReturnMaterialLineVo> result = incomeSettlementService.queryReturnMaterialLine(command);
            responseMsg.setData(result);
        } catch (SPIException e) {
            logger.error(e.getMessage());
            responseMsg.setCode(e.getErrorCode());
            responseMsg.setMsg(e.getErrorMsg());
            responseMsg.setData(com.winit.sms.spi.common.constant.Constants.UPLOAD_FA);
            return ERROR;
        }
        return SUCCESS;

    }

    /**
     * 查询第三方出库单费用信息
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/queryLMAOrderCharge")
    public String queryLMAOrderCharge(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        QueryIncomeSettlementLineByTypeCommand command = SmsUtils.toJavaObject(requestMsg.getData(),
            QueryIncomeSettlementLineByTypeCommand.class);
        IncomeSettlementFieldValidator.validQueryLMAOrderChargeField(SmsUtils.toJsonObject(requestMsg.getData()));
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<IncomeSettlementLineVo> incomeSettlementLineVoList = incomeSettlementService.queryIsExistIncomeSettlementLine(command);
            if (CollectionUtils.isNotEmpty(incomeSettlementLineVoList)) {
                BigDecimal sourceAmt = BigDecimal.ZERO;
                for (IncomeSettlementLineVo incomeSettlementLineVo : incomeSettlementLineVoList) {
                    sourceAmt = sourceAmt.add(incomeSettlementLineVo.getSourceAmt());
                    result.put("sourceCurrency", incomeSettlementLineVo.getSourceCurrency());
                }
                result.put("sourceAmt", sourceAmt);
                QueryCostSettlementLineByTypeCommand queryCostSettlementLineByTypeCommand = SmsUtils.toJavaObject(requestMsg.getData(),
                    QueryCostSettlementLineByTypeCommand.class);
                List<CostSettlementLineVo> costSettlementLineVoList = costSettlementService.queryIsExistCostSettlementLine(queryCostSettlementLineByTypeCommand);
                if (CollectionUtils.isNotEmpty(costSettlementLineVoList) && costSettlementLineVoList.get(0) != null) {
                    result.put("partnerCode", costSettlementLineVoList.get(0).getPartnerCode());
                }
            }
        } catch (SPIException e) {
            logger.error(e.getMessage());
            responseMsg.setCode(e.getErrorCode());
            responseMsg.setMsg(e.getErrorMsg());
            responseMsg.setData(com.winit.sms.spi.common.constant.Constants.UPLOAD_FA);
            return ERROR;
        }
        responseMsg.setData(result);
        return SUCCESS;

    }

}
